package cs.android.view.state;

import java.io.File;
import java.io.IOException;

import cs.android.viewbase.ActivityViewBase;

import static cs.java.lang.Lang.is;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.widget.ImageView;
import cs.android.ActivityView;

public class StateImageView extends ActivityViewBase {

	private static final String IMAGE_FILE_PATH_STATE = "image_path_state";
	private final int viewId;
	private ImageView imageView;
	private File imagePath;

	public StateImageView(ActivityView hasActivity, int viewId) {
		super(hasActivity);
		this.viewId = viewId;
	}

	@Override protected void onCreate() {
		super.onCreate();
		imageView = getImageView(viewId);
	}

	public void clear() {
		imageView.setImageBitmap(null);
		imagePath = null;
	}

	@Override public void onCreateRestore(Bundle state) {
		super.onCreateRestore(state);
		String imageFilePath = state.getString(viewId + IMAGE_FILE_PATH_STATE);
		if (is(imageFilePath)) showImage(new File(imageFilePath));
	}

	@Override public void onSaveInstanceState(Bundle state) {
		super.onSaveInstanceState(state);
		if (is(imagePath)) state.putString(viewId + IMAGE_FILE_PATH_STATE, imagePath.toString());
	}

	public void showImage(File imagePath) {
		this.imagePath = imagePath;
		try {
			Bitmap bitmap = Media.getBitmap(getActivity().getContentResolver(), Uri.fromFile(imagePath));
			imageView.setImageBitmap(bitmap);
			imageView.setVisibility(View.VISIBLE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
